#include "MonitoringChart.h"
#include <QtGui/QResizeEvent>
#include <QtWidgets/QGraphicsScene>
#include <QtCharts/QChart>
#include <QtCharts/QLineSeries>
#include <QtCharts/QSplineSeries>
#include <QtWidgets/QGraphicsTextItem>
#include "callout.h"
#include <QtGui/QMouseEvent>
//#include <QTimer>
#include <QDebug>
#include <QValueAxis>
MonitoringChart::MonitoringChart(QWidget *parent)
    :QGraphicsView(new QGraphicsScene, parent),
     m_coordX(0),
     m_coordY(0),
     m_chart(0),
     m_tooltip(0),
     m_currentX1(0),
     m_currentY1(0),
     m_currentX2(0),
     m_currentY2(0)
{
    setDragMode(QGraphicsView::NoDrag);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // chart
    m_chart = new QChart;
    //m_chart->setMinimumSize(640, 480);
    m_chart->setTitle("温湿度实时数据");
    m_chart->legend()->hide();
    series = new QLineSeries;
//    series->append(1, 3);
//    series->append(4, 5);
//    series->append(5, 4.5);
//    series->append(7, 1);
//    series->append(11, 2);
    m_chart->addSeries(series);

    series2 = new QSplineSeries;
    m_chart->addSeries(series2);

    m_chart->createDefaultAxes();

    m_chart->createDefaultAxes();

        // 获取横纵坐标的坐标轴对象
        QValueAxis *axisX = qobject_cast<QValueAxis*>(m_chart->axisX());
        QValueAxis *axisY = qobject_cast<QValueAxis*>(m_chart->axisY());

        if (axisX && axisY) {
            // 手动设置横纵坐标的最大值
            axisX->setRange(0, 50); // 设置 X 轴范围从 0 到 20
            axisY->setRange(0, 100); // 设置 Y 轴范围从 0 到 10
        }
    m_chart->setAcceptHoverEvents(true);

    setRenderHint(QPainter::Antialiasing);
    scene()->addItem(m_chart);

    m_coordX = new QGraphicsSimpleTextItem(m_chart);
    m_coordX->setPos(m_chart->size().width()/2 - 50, m_chart->size().height());
    m_coordX->setText("X: ");
    m_coordY = new QGraphicsSimpleTextItem(m_chart);
    m_coordY->setPos(m_chart->size().width()/2 + 50, m_chart->size().height());
    m_coordY->setText("Y: ");

    connect(series, &QLineSeries::clicked, this, &MonitoringChart::keepCallout);
    connect(series, &QLineSeries::hovered, this, &MonitoringChart::tooltip);

    connect(series2, &QSplineSeries::clicked, this, &MonitoringChart::keepCallout);
    connect(series2, &QSplineSeries::hovered, this, &MonitoringChart::tooltip);

    this->setMouseTracking(true);
//    QTimer* timer = new QTimer(this);
//    connect(timer, &QTimer::timeout, this, [this, series2]() {
//        // 生成新的数据点
//        m_currentX += 0.5;
//        m_currentY = qrand() % 5 + 1; // 随机生成 Y 值
//        series2->append(m_currentX, m_currentY);
//    });
    //timer->start(1000);
}

MonitoringChart::~MonitoringChart()
{
    qDebug() << "MonitoringChart执行了析构";
    try {
        // 显式断开自己的信号槽连接
        QObject::disconnect(series, &QLineSeries::clicked, this, &MonitoringChart::keepCallout);
        QObject::disconnect(series, &QLineSeries::hovered, this, &MonitoringChart::tooltip);
        QObject::disconnect(series2, &QSplineSeries::clicked, this, &MonitoringChart::keepCallout);
        QObject::disconnect(series2, &QSplineSeries::hovered, this, &MonitoringChart::tooltip);

        // 断开所有子对象的信号槽连接
        QObjectList children = this->children();
        for (QObject* child : children) {
            QObject::disconnect(child);
        }

        // 释放 m_callouts 中的对象
        for (Callout* callout : m_callouts) {
            delete callout;
        }
        m_callouts.clear();

        // 释放 m_tooltip
        delete m_tooltip;
        m_tooltip = nullptr;

        // 释放 m_coordX 和 m_coordY
        delete m_coordX;
        m_coordX = nullptr;
        delete m_coordY;
        m_coordY = nullptr;

        // 释放 m_chart
        delete m_chart;
        m_chart = nullptr;

    } catch (const std::exception& e) {
        // 捕获并处理具体的异常
        qWarning() << "An exception occurred during MonitoringChart destruction: " << e.what();
    }
}
void MonitoringChart::sendChartData(int temperature, int humidity)
{
    qDebug()<<"chart==="<<temperature<<humidity;
//            m_currentX1 += 0.5;
//            m_currentX2 += 0.5;
//            series->append(m_currentX1, temperature);
//            series2->append(m_currentX1, humidity);
            m_currentX1 += 0.5;
           // m_currentY1 = qrand() % 5 + 1; // 随机生成 Y 值
            series->append(m_currentX1, temperature);
            series2->append(m_currentX1, humidity);

}
void MonitoringChart::resizeEvent(QResizeEvent *event)
{
    if (scene()) {
        scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));
        m_chart->resize(event->size());
        m_coordX->setPos(m_chart->size().width()/2 - 50, m_chart->size().height() - 20);
        m_coordY->setPos(m_chart->size().width()/2 + 50, m_chart->size().height() - 20);
        const auto callouts = m_callouts;
        for (Callout *callout : callouts)
            callout->updateGeometry();
    }
    QGraphicsView::resizeEvent(event);
}

void MonitoringChart::mouseMoveEvent(QMouseEvent *event)
{
    m_coordX->setText(QString("X: %1").arg(m_chart->mapToValue(event->pos()).x()));
    m_coordY->setText(QString("Y: %1").arg(m_chart->mapToValue(event->pos()).y()));
    QGraphicsView::mouseMoveEvent(event);
}

void MonitoringChart::keepCallout()
{
    m_callouts.append(m_tooltip);
    m_tooltip = new Callout(m_chart);
}

void MonitoringChart::tooltip(QPointF point, bool state)
{
    if (m_tooltip == 0)
        m_tooltip = new Callout(m_chart);

    if (state) {
        m_tooltip->setText(QString("X: %1 \nY: %2 ").arg(point.x()).arg(point.y()));
        m_tooltip->setAnchor(point);
        m_tooltip->setZValue(11);
        m_tooltip->updateGeometry();
        m_tooltip->show();
    } else {
        m_tooltip->hide();
    }
}
